<?php
/**
 *
 * Author: Lyu
 * Date: 2023/7/25
 * Time: 15:53
 */

namespace App\Service\Core\Admin\Power;

use App\Model\Core\Admin\AdminUserPowerModel;
use App\Model\Core\Admin\AdminUserRoleModel;
use App\Service\Core\CoreBaseService;
use App\Service\ParamsService;
use App\Traits\ModelStoreTrait;

/**
 * @method $this setRoleId($val)
 * @method $this setPowerData(AdminUserPowerStoreItemService $item)
 * @method $this setPermissions($val)
 * @package App\Service\Core\Sys\User\Role
 */
class AdminUserPowerStoreService extends CoreBaseService
{
    use ModelStoreTrait;

    private array $required_param = ['role_id', 'permissions'];

    /**
     *
     * @return array
     * @throws \Throwable
     */
    public function store(): array
    {
        $this->check_required_param($this->required_param);
        if (!empty($this->errors)) {
            return alert_info(1, $this->errors[0], $this->errors);
        }
        $role_id = $this->getParam('role_id');
        $power_data = $this->getParam('power_data')->getItem();
        $permissions = $this->getParam('permissions');
        if (!array_key_exists($permissions, ParamsService::$admin_user_role_data_type)) {
            return alert_info(1, '不支持的权限类型');
        }
        $role_info = AdminUserRoleModel::getInstance()->getOne($role_id);
        if (empty($role_info)) {
            return alert_info(1, '角色不存在');
        }
//        $link_types = array_unique(array_column($power_data, 'link_type'));
//        if ($permissions == ParamsService::Core_USER_ROLE_PERMISSIONS_SELECT && !in_array(ParamsService::Core_USER_POWER_TYPE_DEPT, $link_types)) {
//            return alert_info(1, '选择的部门可见:部门数据不存在');
//        }
        $connection = AdminUserRoleModel::getInstance()->getConnection();
        $connection->beginTransaction();
        //删除原角色权限
        AdminUserPowerModel::getInstance()->deleteRole($role_id);
        //修改角色数据类型
        $res = AdminUserRoleModel::getInstance()->updateOne($role_id, [
            'permissions' => $permissions,
            'updated_at' => date('Y-m-d H:i:s'),
            'updated_by' => $this->operate_by
        ]);
        if ($res === false) {
            $connection->rollBack();
            return alert_info(1, '操作失败：数据库繁忙');
        }
        foreach ($power_data as $item) {
            $item['created_at'] = date('Y-m-d H:i:s');
            $item['created_by'] = $this->operate_by;
            $item['role_id'] = $role_id;
            $res = AdminUserPowerModel::getInstance()->addOne($item);
            if ($res === false) {
                $connection->rollBack();
                return alert_info(2, '操作失败：数据库繁忙');
            }
        }
        $connection->commit();
        return alert_info(0, '操作成功', ['role_id' => $role_id]);
    }
}
